package com.zk.lettcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 有效的括号
 * 使用栈的方式解决
 * @Author: zhang kai
 * @Date: 2021/11/11
 * @Description: https://leetcode-cn.com/problems/valid-parentheses/
 */
public class Practice6 {

    public boolean isValid(String s) {
        if (s.length() % 2 == 1) {
            return false;
        }
        Map<Character, Character> pair = new HashMap<>();
        pair.put('}', '{');
        pair.put(')', '(');
        pair.put(']', '[');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (isLeft(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                if (stack.isEmpty()) {
                    return false;
                } else if (!pair.get(s.charAt(i)).equals(stack.pop())) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }


    public boolean isLeft(char c) {
        switch (c) {
            case '(':
            case '{':
            case '[':
                return true;
            default: return false;
        }
    }
}
